#!/bin/bash

START_DATE="2025-03-18"
END_DATE="2026-12-31"

# 读取已存在的 holidays.json 文件内容
if [ -f holidays.json ]; then
  holidays_json=$(cat holidays.json)
  # 删除最后一个 } 以便添加新的数据
  holidays_json=${holidays_json%,}
else
  holidays_json="{"
fi

current_date=$START_DATE

while [ "$current_date" \< "$END_DATE" ]; do
  # 检查日期是否已经存在于 holidays.json 中
  if echo "$holidays_json" | grep -q "\"$current_date\""; then
    echo "Date $current_date already exists in holidays.json, skipping..."
  else
    echo "Processing date: $current_date"
    response=$(curl -s "http://api.haoshenqi.top/holiday?date=$current_date")
    
    # 使用 grep 和 sed 提取 status 的值
    status=$(echo "$response" | grep -o '"status":[^,}]*' | sed 's/.*://;s/"//g')

    is_holiday=false
    if [ "$status" == "1" ] || [ "$status" == "3" ]; then
      is_holiday=true
    fi

    holidays_json+=", \"$current_date\": $is_holiday"
  fi
  current_date=$(date -I -d "$current_date + 1 day")
done

# Add the end date
if echo "$holidays_json" | grep -q "\"$END_DATE\""; then
  echo "Date $END_DATE already exists in holidays.json, skipping..."
else
  response=$(curl -s "http://api.haoshenqi.top/holiday?date=$END_DATE")
  status=$(echo "$response" | grep -o '"status":[^,}]*' | sed 's/.*://;s/"//g')

  is_holiday=false
  if [ "$status" == "1" ] || [ "$status" == "3" ]; then
    is_holiday=true
  fi

  holidays_json+=", \"$END_DATE\": $is_holiday"
fi

holidays_json+="}"

echo "$holidays_json" > holidays.json